// 传入任意 http/https 地址即可
export function downloadFile(fileUrl, fileName = '') {
  return new Promise((resolve, reject) => {
    // 1. 创建下载任务
    const task = plus.downloader.createDownload(
      fileUrl,
      {
        filename: `_downloads/${fileName || Date.now()}.tmp` // 先放临时目录
      },
      (t, status) => {
        if (status === 200) {
          // 2. 下载完成 → 移动到公共下载目录，让系统媒体库扫描到
          const newPath = plus.io.convertLocalFileSystemURL(`_downloads/${fileName}`);
          plus.io.resolveLocalFileSystemURL(
            t.filename,
            (entry) => {
              entry.moveTo(
                plus.io.resolveLocalFileSystemURL('_downloads/'),
                fileName,
                (movedEntry) => {
                  // 3. 通知系统扫描（可选，立即在“文件管理/通知栏”可见）
                  plus.io.requestFileSystem(
                    plus.io.PUBLIC_DOWNLOADS,
                    (fs) => {
                      fs.root.getFile(
                        movedEntry.name,
                        { create: false },
                        (fileEntry) => {
                          plus.android.importClass('android.media.MediaScannerConnection');
                          const Main = plus.android.runtimeMainActivity();
                          MediaScannerConnection.scanFile(
                            Main,
                            [fileEntry.fullPath],
                            null,
                            () => resolve(fileEntry.fullPath)
                          );
                        }
                      );
                    }
                  );
                },
                (e) => reject(e)
              );
            },
            (e) => reject(e)
          );
        } else {
          reject(new Error('下载失败 status=' + status));
        }
      }
    );
    // 4. 开始下载
    task.start();
    // 5. 可选：把进度抛给页面
    task.addEventListener('statechanged', (t) => {
      if (t.state === 3) {
        const percent = Math.floor((t.downloadedSize / t.totalSize) * 100);
        uni.$emit('downloadProgress', percent);
      }
    });
  });
}